const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const { addSocketId, getSocketId, deleteSocketId } = require('./utils/zym-socketIoUtils');
const scheduler = require('./services/scheduler.service');
const moment = require('moment-timezone');
// 引入路由
const examRoutes = require('./routes/exam.routes');
const taskRoutes = require('./routes/task.routes');
const markPaperRoutes = require('./routes/markPaper.routes');
const recheckRequestRoutes = require('./routes/recheckRequest.routes');
const notificationRoutes = require('./routes/notification.routes');
const recheckRequestManageRoutes = require('./routes/recheckRequestManage.routes');
const recheckTaskRoutes = require('./routes/recheckTask.routes');
const backupRoutes = require('./routes/backup.routes');
const scoreAnalysisExportRoutes = require('./routes/scoreAnalysisExport.routes');
const fileUpload = require('express-fileupload');
// 加载环境变量
dotenv.config();

// 创建Express应用
const app = express();

// 中间件
app.use(cors());
app.use(fileUpload({
  limits: { fileSize: 500 * 1024 * 1024 }, // 500MB文件大小限制
  useTempFiles: true, // 使用临时文件而不是内存
  tempFileDir: './temp_uploads/', // 临时文件目录
  debug: true, // 开启调试模式，输出详细日志
  abortOnLimit: true, // 超出大小限制时中断请求
  createParentPath: true // 自动创建父目录
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 注册路由
app.use('/taskScheduling', examRoutes);
app.use('/taskManage', taskRoutes);   
app.use('/markPaper', markPaperRoutes);
app.use('/recheckRequest', recheckRequestRoutes);
app.use('/notification', notificationRoutes);
app.use('/recheckRequestManage', recheckRequestManageRoutes);
app.use('/recheckTask', recheckTaskRoutes);
app.use('/backup', backupRoutes);
app.use('/scoreAnalysisExport', scoreAnalysisExportRoutes);
// 数据库连接测试路由
app.get('/api/db-test', async (req, res) => {
  try {
    const { PrismaClient } = require('@prisma/client');
    const prisma = new PrismaClient();
    await prisma.$connect();
    console.log('数据库连接成功');
    res.json({ message: '数据库连接成功' });
    await prisma.$disconnect();
  } catch (error) {
    console.error('数据库连接失败:', error);
    res.status(500).json({ message: '数据库连接失败', error: error.message });
  }
});

// 根路由
app.get('/', (req, res) => {
  res.json({ message: '欢迎使用在线考试系统API' });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
    // 初始化定时任务
   // scheduler.initScheduler();
 

}); 

// 创建socket.io实例
const io = require('socket.io')(server);

// 记录登录用户的tokenId, socketId
const userList = [];

io.on('connection', function(socket) {

  // 监听用户登录
  socket.on("user_login", function (info) {
    const {  userId, socketId } = info;
    addSocketId(userList, { userId, socketId});
    if (process.env.NODE_ENV === 'development') {
      displayUserInfo();
    }
  });

  // 监听用户断开连接
  socket.on('disconnect', function() {
    console.log('user disconnected   ', socket.id);
    deleteSocketId(userList, socket.id);
    if (process.env.NODE_ENV === 'development') {
        displayUserInfo();
    }
  });

})


function displayUserInfo() {
  console.log('当前登录用户信息：');
  console.log(userList);
}


module.exports = {
  io,
  userList
}

